package model;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-09-08
 * Time: 9:05
 */
public class Demo2 {

    public static void main(String[] args) throws Exception {
        // 创建 1 个原子类，用于多线程计数
        AtomicInteger atomicInteger = new AtomicInteger(1);
        // 创建 1 个初始值为 10 的线程同步工具类
        CountDownLatch latch = new CountDownLatch(10);
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    // 生成一个 0-9999之间的随机数，表示比赛时间
                    Thread.sleep((long) (Math.random() * 10000));
                    System.out.println("第: "+atomicInteger.getAndIncrement()+"选手完成了比赛");
                    latch.countDown();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        for (int i = 0; i < 10; i++) {
            new Thread(r).start();
        }
        // 必须等到 10 人全部回来
        latch.await();
        System.out.println("比赛结束");
    }

}
